package generator;

import generator.meta.ClassMeta;
import generator.meta.FieldMeta;
import generator.util.HibernateBeanReflectUtils;
import generator.util.JpaAnnotationUtils;
import generator.util.PackageScan;
import generator.util.ReflectUtil;

import java.lang.reflect.Field;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: sunguangzhu
 * Date: 13-8-9
 * Time: 上午9:23
 * To change this template use File | Settings | File Templates.
 */
public class BeanGenerator extends Generator implements IGenerrator {
    @Override
    public void generate(String templateName, String packageName,String classPackage) throws Exception {
        Set<Class<?>> classes = PackageScan.getClasses(classPackage);
        for (Class<?> clazz : classes) {
            ClassMeta classMeta = new ClassMeta();
            classMeta.setPackageName(packageName);
            classMeta.setClassName(clazz.getSimpleName());
            classMeta.setBaseClassName(clazz.getSuperclass().getSimpleName());
            classMeta.setTableName(HibernateBeanReflectUtils.getTableName(clazz));
            classMeta.setCatalog("commonproject");
            List<FieldMeta> fieldMetas = new ArrayList<FieldMeta>();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                FieldMeta fieldMeta = new FieldMeta();
                fieldMeta.setName(field.getName());
                String fieldTypeName =  field.getType().getName();
                if(fieldTypeName.contains(classPackage)){
                    fieldMeta.setType(field.getGenericType().toString().replace("class","").replace(classPackage,packageName));
                }else if(fieldTypeName.contains("java.util")){
                    fieldMeta.setType(field.getGenericType().toString().replace("class","").replace(classPackage,packageName));
                }else{
                    fieldMeta.setType(fieldTypeName);
                }
                fieldMeta.setUpperName((ReflectUtil.parSetName(field.getName())).replace("set", ""));
                MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);
                fieldMeta.setAnnotationFlag(annotation.relation());
                List<String> list = JpaAnnotationUtils.getJapAnnotationList(fieldMeta.getAnnotationFlag(), field, clazz);
                fieldMeta.setJpaAnnotations(list);
                fieldMeta.setComment(annotation.comments());
                fieldMetas.add(fieldMeta);
            }
            classMeta.setFields(fieldMetas);
            Map root = new HashMap();
            root.put("bean", classMeta);
            super.generate(root,templateName, classMeta.getClassName(),packageName);
        }
    }
}
